<?php

require_once '1_utilities.inc.php';
require_once 'mysql_db.inc.php';
require_once 'matchas.inc.php';


$match_action = get_parameter('match_action');

if ($match_action == 'start') {
	$created_match_id = create_match();
	echo "Created new match $created_match_id <br/>";
	
	}


$match_action = get_parameter('match_action');

$participants_action = get_parameter('participants_action');

if ($participants_action == 'Join'){
        $match_id = get_parameter('match_id');
        foreach( get_parameter('players') as $player_id) {
			   $participant_in_match = sql_get("SELECT * FROM Participants WHERE match_id={$match_id} AND player_id={$player_id}");
        				if ( empty( $participant_in_match )){
           mysql_query("INSERT INTO Participants (match_id,player_id ) VALUES ($match_id, $player_id)") or die(mysql_error());
		   $query = "SELECT * FROM Participants WHERE match_id={$match_id}";
		   $participants_in_match = sql_get($query);
		   $players_count = count($participants_in_match);
		   mysql_query("UPDATE Matches SET Players_cnt = $players_count WHERE  `ID` = {$match_id}");
		   mysql_query("UPDATE Matches SET Status=1 WHERE Players_cnt>=2") or die(mysql_error());
        											}
			}
}

?>

<html>


<form action="<?php echo $_SERVER['PHP_SELF'];  ?>"  method="POST">
Matches running: <?php echo get_max_match_id() ?> <br />
<input type="submit" name="match_action" value="start" />
</form>


<form action="<?php echo $_SERVER['PHP_SELF'];  ?>" method="post">
<h4> Nonstarted matches </h4> <?php get_matches() ?> <br/>
<h4> Players </h4> <?php get_players() ?> <br/>
<input type="submit" name="participants_action" value="Join" />
</form>
</html>
